package org.stayfool.nio;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

import org.junit.Test;
import org.stayfool.nio.enums.FileAccess;
import org.stayfool.nio.util.FileUtil;

public class NIOFileReadAndWrite {

	String filepath = "random-file.txt";
	String toFile = "to-file.txt";

	// NIO read
	@Test
	public void read() {
		try {
			RandomAccessFile f = new RandomAccessFile(new File(filepath), FileAccess.READ_ONLY.code());

			FileChannel c = f.getChannel();
			ByteBuffer b = ByteBuffer.allocate(1024);

			while (c.read(b) > -1) {
				b.flip();
				while (b.hasRemaining()) {
					System.out.print((char) b.get());
				}
				b.clear();
			}
			f.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// NIO write
	@Test
	public void write() {
		try {
			RandomAccessFile f = new RandomAccessFile(new File(filepath), FileAccess.READ_ONLY.code());
			RandomAccessFile t = new RandomAccessFile(new File(toFile), FileAccess.READ_AND_WRITE.code());

			FileChannel fc = f.getChannel();
			FileChannel tc = t.getChannel();

			fc.transferTo(0, f.length(), tc);

			f.close();
			t.close();

			FileUtil.show(toFile);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
